<?php
/**
 * @todo 快递打印模版、发货单打印模版
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/25
 * Time: 13:15
 */
namespace app\web\service;

use app\web\model\Express;
use app\web\model\PrintTemplate;
use think\facade\Log;

class TemplateService{
    /**
     * @todo 获取店铺打印模版
     * @author ZJF
     */
    public function getTemplate($shop_id = 0,$type = 0){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        if(empty($type) || !is_numeric($type) || !in_array($type,[1,2])){
            return array_response([],1,'无效的模版类型');
        }
        try{
            if($type == 1){
                //获取快递单打印模版
                $res = $this->getExpressTemp($shop_id);
            }
            elseif($type == 2){
                //获取发货单打印模版
                $res = $this->getInvoiceTemp($shop_id);
            }
            return $res;
        }
        catch(\Exception $e){
            $error = array(
                'message'=>$e->getMessage(),
                'url'=>$e->getFile(),
                'code'=>$e->getCode(),
                'line'=>$e->getLine()
            );
            Log::write(json_encode($error,JSON_UNESCAPED_UNICODE),"ERROR");
            return array_response([],1,"异常错误");
        }
    }

    /**
     * @todo 获取快递模版
     * @param int $shop_id 店铺ID
     */
    private function getExpressTemp($shop_id = 0){
        $where = "shop_id='{$shop_id}' AND is_del=0 AND class=1 AND type=1";
        $order = "sort DESC,id ASC";
        $print_model = new PrintTemplate();
        $temp_list = $print_model->where($where)->order($order)->select();
        if($temp_list->isEmpty()){
            //无数据，新增
            //新增四个模版
            $add_data = [];//新增数据
            $now_time = date('Y-m-d H:i:s');
            $platform_temp_list = $this->getPlatformTemp(1);
            if(empty($platform_temp_list)){
                return [];
            }
            foreach($platform_temp_list as &$val){
                unset($val['id']);//去掉ID
                $val['shop_id'] = $shop_id;
                $val['ctime'] = $now_time;
                $val['mtime'] = $now_time;
                $add_data[] = $val;
            }
            $res = $print_model->insertAll($add_data);
            $temp_list = $print_model->where($where)->order($order)->select();
        }
        return ObjectToArray($temp_list);
    }


    /**
     * @todo 获取发货单模版
     * @param int $shop_id 店铺ID
     */
    private function getInvoiceTemp($shop_id = 0){
        $where = "shop_id='{$shop_id}' AND is_del=0 AND class=2";
        $order = "sort DESC,id ASC";
        $print_model = new PrintTemplate();
        $temp_list = $print_model->where($where)->order($order)->select();
        if($temp_list->isEmpty()){
            //无数据，新增
            $add_data = [];//新增数据
            $now_time = date('Y-m-d H:i:s');
            $platform_temp_list = $this->getPlatformTemp(2);
            if(empty($platform_temp_list)){
                return [];
            }
            foreach($platform_temp_list as &$val){
                unset($val['id']);//去掉ID
                $val['shop_id'] = $shop_id;
                $val['ctime'] = $now_time;
                $val['mtime'] = $now_time;
                $add_data[] = $val;
            }
            $res = $print_model->insertAll($add_data);
            $temp_list = $print_model->where($where)->order($order)->select();
        }
        return ObjectToArray($temp_list);
    }

    /**
     * @todo 平台默认模版
     * @author ZJF
     * @param $type int 1快递单、2发货单
     */
    public function getPlatformTemp($type = 1){
        if(empty($type) || !is_numeric($type) || !in_array($type,[1,2])){
            return array_response([],1,"无效的模版类型");
        }
        $print_model = new PrintTemplate();
        $list = [];
        if($type == 1){
            $list = $print_model
                    ->where("shop_id=0 AND class=1 AND type=1 AND is_del=0")
                    ->order("sort DESC,id ASC")
                    ->limit(0,4)
                    ->select();
        }
        elseif($type == 2){
            $list = $print_model
                    ->where("shop_id=0 AND class=2 AND is_del=0")
                    ->order("sort DESC,id ASC")
                    ->select();
        }
        return ObjectToArray($list);
    }

    /**
     * @todo 全部物流信息
     * @author ZJF
     */
    public function getExpressList(){
        $express_model = new Express();
        $list = $express_model
                ->field("express.id,express.name,express.company_no,express.company_phone")
//                ->leftJoin("print_template","print_template.express_id=express.id AND print_template.is_del=0 AND print_template.shop_id=0")
                ->where("express.is_del=0")
                ->order("express.sort DESC,express.id ASC")
                ->select();
        return ObjectToArray($list);
    }

    /**
     * @todo 店铺添加快递模版
     * @author ZJF
     */
    public function addExpressTemp($shop_id = 0,$express_id = 0){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        if(empty($express_id) || !is_numeric($express_id)){
            return array_response([],1,"无效的快递ID");
        }
        $print_model = new PrintTemplate();
        $shop_where = array(
            'shop_id'=>$shop_id,
            'is_del'=>0,
            'class'=>1,
            'type'=>1,
            'express_id'=>$express_id
        );
        $shop_temp_info = $print_model->where($shop_where)->find();
        $shop_temp_info = ObjectToArray($shop_temp_info);
        if(!empty($shop_temp_info)){
            return array_response([],1,"该模版已存在");
        }
        //不存在，添加
        $temp_where = array(
            'shop_id'=>0,
            'is_del'=>0,
            'class'=>1,
            'type'=>1,
            'express_id'=>$express_id
        );
        $temp_info = $print_model->field("express_id,express_name,class,type,lodop_template,image_url,sort,is_default")->where($temp_where)->find();
        $temp_info = ObjectToArray($temp_info);
        if(empty($temp_info)){
            return array_response([],1,"物流模版不存在");
        }
        $temp_info['shop_id'] = $shop_id;
        $temp_info['ctime'] = date('Y-m-d H:i:s');
        $temp_info['mtime'] = date('Y-m-d H:i:s');
        $res = $print_model->insert($temp_info);
        if(false === $res){
            return array_response([],1,"添加失败");
        }
        return true;
    }

    /**
     * @todo 设置默认模版
     * @author ZJF
     */
    public function setInvoiceDef($shop_id = 0,$temp_id = 0){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        if(empty($temp_id) || !is_numeric($temp_id)){
            return array_response([],1,"无效的模版ID");
        }
        $print_model = new PrintTemplate();
        $where = array(
            'shop_id'=>$shop_id,
            'id'=>$temp_id,
            'is_del'=>0,
            'class'=>2
        );
        $temp_info = $print_model->where($where)->find();
        $temp_info = ObjectToArray($temp_info);
        if(empty($temp_info)){
            return array_response([],1,"无效的模版信息");
        }
        if($temp_info['is_default'] == 1){
            return array_response([],1,"已是默认发货单模版");
        }
        //取消原来的默认模版
        $update_where = array(
            'shop_id'=>$shop_id,
            'is_default'=>1,
            'class'=>2
        );
        $data = array(
            'is_default'=>0,
            'mtime'=>date('Y-m-d H:i:s')
        );
        $res = $print_model->where($update_where)->save($data);
        if(false===$res){
            return array_response([],1,"解除默认设置失败");
        }
        //设置默认模版
        $update_where['id'] = $temp_id;
        $update_where['is_default'] = 0;
        $data['is_default'] = 1;
        $res = $print_model->where($update_where)->save($data);
        if(false===$res){
            return array_response([],1,"设置默认设置失败");
        }
        return true;
    }

    /**
     * @todo 获取店铺设置的默认发货单
     * @author ZJF
     */
    public function getInvoiceDef($shop_id = 0){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        $print_model = new PrintTemplate();
        $where = array(
            'shop_id'=>$shop_id,
            'is_default'=>1,
            'is_del'=>0,
            'class'=>2
        );
        $temp_info = $print_model->where($where)->find();
        $temp_info = ObjectToArray($temp_info);
        if(empty($temp_info)){
            return array_response([],1,"未设置发货单模版");
        }
        return $temp_info;
    }
}